﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using LogScrubberCommon;
using System.Configuration;
using System.IO;

namespace LogScrubberService
{
    public partial class logScrubberService : ServiceBase
    {
        public logScrubberService()
        {
            InitializeComponent();
        }

        Timer mainTimer = new Timer();
       
        LogScrubberConfiguration config = null;


        protected override void OnStart(string[] args)
        {
            EventLog.WriteEntry("Log Scrubber Service started.");


            LoadConfig();
            mainTimer.Enabled = true; 
            mainTimer.Interval = 60 * 60 * 1000; 
            mainTimer.Elapsed += new ElapsedEventHandler(mainTimer_Elapsed);
            ScubLogs(); 
        }

        void mainTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            ScubLogs(); 
        }

        private bool ProcessConfig()
        {
            return true;
        }

        private void LoadConfig()
        {
            try
            {

                config = (LogScrubberConfiguration)ConfigurationManager.GetSection("LogScrubber");

            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("There was an error loading the configuration file. Please re-run the administration tool.", EventLogEntryType.Error, 0);

                throw new Exception("Error Loading Configuration", ex);
            }



        }

        protected override void OnStop()
        {
            EventLog.WriteEntry("Log Scrubber Service stopped.");
        }

        /// <summary>
        /// Called when [start]. Used for debegging
        /// </summary>
        public void OnStart()
        {
            this.OnStart(null);
        }

        /// <summary>
        /// Used exclusively for debugging. 
        /// </summary>
        public class Entry
        {

            static void Main()
            {

#if DEBUG

                logScrubberService myService = new logScrubberService();

                myService.OnStart();

                System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

#endif

            }

        }

        public void ScubLogs()
        {
            // Build Scrub Keys
            List<String> scrubKeys = new List<String>(); 
            
            foreach (LogScrubKeyElement key in config.ScrubKeys)
            {
                scrubKeys.Add(key.Value); 
            }
                        
            // Check to see if source directory exists
            if (System.IO.Directory.Exists(config.SourceDirectory.Path))
            {
                // Check to see if there are any files to scrub
                foreach (String file in System.IO.Directory.GetFiles(config.SourceDirectory.Path, config.SourceDirectory.Extension))
                {

                    try
                    {
                        // See if we can lock files by renaming them to .processing

                        System.IO.File.Move(file, file + ".processing");

                        try
                        {
                            LogScrubberCommon.Scrubber.Scrub(file + ".processing", config.DestinationDirectory.Path + file.Substring(file.LastIndexOf("\\")), scrubKeys);

                            try
                            {
                                if (config.SaveOriginal)
                                    System.IO.File.Move(file + ".processing", config.DestinationDirectory.Path + file.Substring(file.LastIndexOf("\\")) + ".original");

                                System.IO.File.Delete(file + ".processing"); 
                            }
                            catch (Exception ex)
                            {
                                EventLog.WriteEntry("Error Moving Original File " + ex.Message);
                            }
                        }
                        catch (Exception ex)
                        {
                            EventLog.WriteEntry("Error Scrubbing Logs " + ex.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        EventLog.WriteEntry("Error Locking File " + ex.Message);
                         
                    }
                    
                    // scrub the files .processing and write them to the directory. 

                  

                       
                    
                }
            }
            else
            {
                throw new FileNotFoundException(config.SourceDirectory.Path); 
            }
        }

    }
}
